﻿using Microsoft.Xna.Framework;
using ShevaEngine.Core.Modules.Graphics;
using ShevaEngine.Core.Modules.Graphics.Cameras;
using ShevaEngine.Core.Modules.Scenes;
using System;

namespace ShevaEngine.Core.Modules.Scenes
{
    /// <summary>
    /// Scene node level of detail.
    /// </summary>
    public class SceneNodeLevelOfDetail : SceneNode
    {
        /// <summary>Switch in distance.</summary>
        public float SwitchInDistance;
        /// <summary>Switch out distance.</summary>
        public float SwitchOutDistance;
        /// <summary>Center point.</summary>
        public Vector3 CenterPoint;
        /// <summary>Distance.</summary>
        private Single Distance;

        /// <summary>
        /// Override Add in rendering pipeline method.
        /// </summary>
        /// <param name="renderingPipeline"></param>
        /// <param name="worldMatrix"></param>
        public override bool AddInRenderingPipeline(RenderingPipeline renderingPipeline, Camera camera, Matrix worldMatrix)
        {
            if (!this.BoundingSphere.Transform(worldMatrix).Intersects(camera.Frustum))
                return false;

            this.Distance = Vector3.DistanceSquared(camera.Position, this.CenterPoint + worldMatrix.Translation);

            if (this.SwitchOutDistance >= this.Distance || this.SwitchInDistance < this.Distance)
                return false;

            for (int i = this.Count - 1; i >= 0; i--)
                if (this[i].AddInRenderingPipeline(renderingPipeline, camera, worldMatrix))
                    return true;

            return true;
        }
    }
}
